using System.Text;
using System.Text.Json;
using RSCore;

namespace _ReplaceString_.RSConfigs;

public class LocalConfig
{
	private static LocalConfig? _config;

	public Dictionary<string, List<PackageID>> EnabledPackage { get; set; } = new();

	private void Save()
	{
		File.WriteAllText(ModHelper.ConfigPath, JsonSerializer.Serialize(this, new JsonSerializerOptions()
		{
			WriteIndented = true,
		}), Encoding.UTF8);
	}

	private static LocalConfig Load()
	{
		if (File.Exists(ModHelper.ConfigPath))
		{
			var json = File.ReadAllText(ModHelper.ConfigPath, Encoding.UTF8);
			try
			{
				return JsonSerializer.Deserialize<LocalConfig>(json) ?? new();
			}
			catch
			{
			}
		}
		return new LocalConfig();
	}

	public static List<PackageID> GetPackages(string mod)
	{
		_config = Load();
		if (!_config.EnabledPackage.TryGetValue(mod, out var list))
		{
			list ??= new List<PackageID>();
		}
		return list;
	}

	public static void SetPackages(string mod, List<PackageID> packages)
	{
		_config = Load();
		_config.EnabledPackage[mod] = packages;
		_config.Save();
	}
}